import axios from 'axios'
import {getLocalStorage} from "./auth"
import {Notify} from "vant";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
      if (getLocalStorage()) {
        // console.log(config)
        // do something before request is sent
        config.params = {
          ...config.params,
          // 这个每个接口 都需要传递，用来获取个人定制的数据
          cookie: getLocalStorage()
        }
        // console.log(config)
      }
      return config
    },
    error => {
      return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
      const res = response.data
      // if the custom code is not 20000, it is judged as an error.
      if (res.code !== 200) {
        // 返回错误信息
        return Promise.reject(res)
      } else {
        return res
      }
    },
    error => {
      console.log(error)
      if (error.response?.data?.code === -460)
        Notify({
          message: '请稍后在试',
          background: 'red',
          color: 'white'
        })
      return Promise.reject(error.response.data)
    }
)

export default service
